/*
 * Copyright (c) 田梓萱 2021-2022.
 * All Rights Reserved.
 * All codes are protected by China's regulations on the protection of computer software, and infringement must be investigated.
 * 版权所有 (c) 田梓萱 2021-2022.
 * 所有代码均受中国《计算机软件保护条例》保护，本项目已获得软著.
 */

package com.xcl.calculator.slice;

import com.huawei.agconnect.crash.AGConnectCrash;
import com.xcl.calculator.Dialog.MyToastDialog;
import com.xcl.calculator.Preference_RW;
import com.xcl.calculator.ResourceTable;
import com.xcl.calculator.XLog;
import com.xcl.calculator.slice.QinQiCal.FamilyAbilitySlice;
import com.xcl.calculator.slice.Time.TimeChaCalAbilitySlice;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Component;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.service.WindowManager;
import ohos.data.distributed.common.KvManagerConfig;
import ohos.data.distributed.common.KvManagerFactory;
import ohos.distributedhardware.devicemanager.DeviceInfo;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.multimodalinput.event.KeyEvent;
import ohos.multimodalinput.event.MmiPoint;
import ohos.multimodalinput.event.TouchEvent;

/**
 * The type Cai dan ability slice.
 *
 * @author Xcl
 * @date 2022 /1/2
 * @package com.xcl.calculator.slice
 */
public class CaiDanAbilitySlice extends AbilitySlice implements Component.TouchEventListener {
    /**
     * The constant label.
     */
    private static final HiLogLabel label = new HiLogLabel(HiLog.LOG_APP, 0x00234, "CaiDanAbilitySlice");
    /**
     * The constant text.
     */
    private static String text = null;
    /**
     * The constant text1.
     */
    private static String text1 = null;
    /**
     * The Devicetype.
     */
    private final int Devicetype = 999666;
    /**
     * The Starx.
     */
    private float starx;
    /**
     * The Stary.
     */
    private float stary;
    /**
     * The Endx.
     */
    private float endx;
    /**
     * The Endy.
     */
    private float endy;

    /**
     * 开始
     *
     * @param intent the intent
     */
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        try {
            XLog.pd_pd = Preference_RW.ff7_r();
            this.getWindow().addFlags(WindowManager.LayoutConfig.MARK_ALLOW_EXTEND_LAYOUT);
            ohos.data.distributed.device.DeviceInfo localDeviceInfo = KvManagerFactory.getInstance()
                    .createKvManager(new KvManagerConfig((this))).getLocalDeviceInfo();
            int localDeviceType = Integer.parseInt(localDeviceInfo.getType());
            if (localDeviceType == DeviceInfo.DeviceType.PHONE.value()) {
                this.setUIContent(ResourceTable.Layout_caidanm);
                XLog.info(label, "当前设备类型为手机");
            } else if (localDeviceType == DeviceInfo.DeviceType.TABLET.value()) {
                this.setUIContent(ResourceTable.Layout_caidant);
                XLog.info(label, "当前设备类型为平板");
            } else {
                XLog.warn(label, "暂不支持您的设备:(" + localDeviceInfo.getType() + ")");
                this.terminateAbility();
            }
            this.findComponentById(ResourceTable.Id_caidanm).setTouchEventListener(this);
            this.findComponentById(ResourceTable.Id_cal_button).setClickedListener(new Component.ClickedListener() {
                @Override
                public void onClick(Component v) {
                    CaiDanAbilitySlice.this.ShowDialog("您将进入科学计算器菜单,右划可回到主菜单");
                    /*无参--页面跳转开始*/
                    Intent intent1 = new Intent();
                    Operation operation = new Intent.OperationBuilder()
                            .withDeviceId("")
                            .withBundleName(CaiDanAbilitySlice.this.getBundleName())
                            .withAbilityName("com.xcl.calculator.Ability.Calculate.CalMenuAbility")
                            .build();// 通过Intent中的OperationBuilder类构造operation对象，指定设备标识（空串表示当前设备）、应用包名、Ability名称
                    intent1.setOperation(operation);// 把operation设置到intent中
                    CaiDanAbilitySlice.this.startAbility(intent1);
                    /*页面跳转结束--无参*/
                    //Intent intent1 = new Intent();
                    //CaiDanAbilitySlice.this.present(new Cal0AbilitySlice(), intent1);
                    CaiDanAbilitySlice.this.onBackPressed();
                }
            });
            this.findComponentById(ResourceTable.Id_calqq_button).setClickedListener(new Component.ClickedListener() {
                @Override
                public void onClick(Component v) {
                    CaiDanAbilitySlice.this.ShowDialog("您将进入亲戚称谓计算,右划可回到主菜单");
                    /*无参--页面跳转开始*/
                    Intent intent2 = new Intent();
                    CaiDanAbilitySlice.this.present(new FamilyAbilitySlice(), intent2);
                    /*Operation operation = new Intent.OperationBuilder()
                            .withDeviceId("")
                            .withBundleName(getBundleName())
                            .withAbilityName("com.xcl.calculator.Ability.QinQiCal.FamilyAbility")
                            .build();// 通过Intent中的OperationBuilder类构造operation对象，指定设备标识（空串表示当前设备）、应用包名、Ability名称
                    intent2.setOperation(operation);// 把operation设置到intent中
                    startAbility(intent2);
                    页面跳转结束--无参*/
                    CaiDanAbilitySlice.this.onBackPressed();
                }
            });
            this.findComponentById(ResourceTable.Id_dwhs_button).setClickedListener(new Component.ClickedListener() {
                @Override
                public void onClick(Component v) {
                    CaiDanAbilitySlice.this.ShowDialog("您将进入单位换算,右划可回到主菜单");
                    Intent intent3 = new Intent();
                    /*无参--页面跳转开始
                    CaiDanAbilitySlice.this.present(new DWZH1AbilitySlice(), intent3);*/
                    Operation operation = new Intent.OperationBuilder()
                            .withDeviceId("")
                            .withBundleName(CaiDanAbilitySlice.this.getBundleName())
                            .withAbilityName("com.xcl.calculator.Ability.DanWeiCal.DWZH1Ability")
                            .build();// 通过Intent中的OperationBuilder类构造operation对象，指定设备标识（空串表示当前设备）、应用包名、Ability名称
                    intent3.setOperation(operation);// 把operation设置到intent中
                    CaiDanAbilitySlice.this.startAbility(intent3);
                    /*页面跳转结束--无参*/
                    CaiDanAbilitySlice.this.onBackPressed();
                }
            });
            /*this.findComponentById(ResourceTable.Id_cdjzzh_button).setClickedListener(new Component.ClickedListener() {
                @Override
                public void onClick(Component v) {
                    CaiDanAbilitySlice.this.ShowDialog("您将进入进制转换界面,右划可回到主菜单");
                    无参--页面跳转开始
                    Intent intent4 = new Intent();
                    CaiDanAbilitySlice.this.present(new JZZhuanHuanAbilitySlice(), intent4);
                    *//*Operation operation = new Intent.OperationBuilder()
                            .withDeviceId("")
                            .withBundleName(getBundleName())
                            .withAbilityName("com.xcl.calculator.Ability.Jinzhi.ZhuanHuanAbility")
                            .build();// 通过Intent中的OperationBuilder类构造operation对象，指定设备标识（空串表示当前设备）、应用包名、Ability名称
                    intent4.setOperation(operation);// 把operation设置到intent中
                    startAbility(intent4);
                    页面跳转结束--无参
                    CaiDanAbilitySlice.this.onBackPressed();
                }
            });*/
            this.findComponentById(ResourceTable.Id_cdtime_button).setClickedListener(new Component.ClickedListener() {
                @Override
                public void onClick(Component v) {
                    CaiDanAbilitySlice.this.ShowDialog("您将进入时间差、时间戳计算,右划可回到主菜单");
                    /*无参--页面跳转开始*/
                    Intent intent5 = new Intent();
                    CaiDanAbilitySlice.this.present(new TimeChaCalAbilitySlice(), intent5);
                    /*Operation operation = new Intent.OperationBuilder()
                            .withDeviceId("")
                            .withBundleName(getBundleName())
                            .withAbilityName("com.xcl.calculator.Ability.Time.TimeChaCalAbility")
                            .build();// 通过Intent中的OperationBuilder类构造operation对象，指定设备标识（空串表示当前设备）、应用包名、Ability名称
                    intent5.setOperation(operation);// 把operation设置到intent中
                    startAbility(intent5);
                    页面跳转结束--无参*/
                    CaiDanAbilitySlice.this.onBackPressed();
                }
            });
            this.findComponentById(ResourceTable.Id_cdabout_button).setClickedListener(new Component.ClickedListener() {
                @Override
                public void onClick(Component v) {
                    CaiDanAbilitySlice.this.ShowDialog("您将进入关于界面,右划可回到主菜单");
                    /*无参--页面跳转开始
                    try {
                        throw new Exception("HiAnalyticsSDK 测试");//TODO:仅供测试崩溃
                    } catch (Exception e) {
                        AGConnectCrash.getInstance().setUserId(Preference_RW.uuid.toString());
                        AGConnectCrash.getInstance().recordException(e);
                        e.printStackTrace();
                    }*/

                    Intent intent6 = new Intent();
                    CaiDanAbilitySlice.this.present(new AboutAbilitySlice(), intent6);
                    //TODO:测试后恢复

                     /*Operation operation = new Intent.OperationBuilder()
                            .withDeviceId("")
                            .withBundleName(getBundleName())
                            .withAbilityName("com.xcl.calculator.Ability.AboutAbility")
                            .build();// 通过Intent中的OperationBuilder类构造operation对象，指定设备标识（空串表示当前设备）、应用包名、Ability名称
                    intent6.setOperation(operation);// 把operation设置到intent中
                    startAbility(intent6);
                   页面跳转结束--无参*/
                    CaiDanAbilitySlice.this.onBackPressed();
                }
            });
            this.findComponentById(ResourceTable.Id_fbsbq_button).setClickedListener(new Component.ClickedListener() {
                @Override
                public void onClick(Component v) {
                    CaiDanAbilitySlice.this.ShowDialog("您将进入便签界面,右划可回到主菜单");

                    /*无参--页面跳转开始*/
                    Intent intent = new Intent();
                    Operation operation = new Intent.OperationBuilder()
                            .withDeviceId("")
                            .withBundleName(CaiDanAbilitySlice.this.getBundleName())
                            .withAbilityName("com.xcl.calculator.Ability.BianQian.BianQianShowAbility")
                            .build();// 通过Intent中的OperationBuilder类构造operation对象，指定设备标识（空串表示当前设备）、应用包名、Ability名称
                    intent.setOperation(operation);// 把operation设置到intent中
                    CaiDanAbilitySlice.this.startAbility(intent);
                    CaiDanAbilitySlice.this.onBackPressed();
                    /*页面跳转结束--无参*/
                }
            });
        } catch (Exception e) {
            AGConnectCrash.getInstance().recordException(e);
            XLog.error(label, e.getMessage());
        }
    }

    /**
     * 移动
     *
     * @param component  the component
     * @param touchEvent the touch event
     * @return boolean boolean
     */
    @Override
    public boolean onTouchEvent(Component component, TouchEvent touchEvent) {
        try {
            int action = touchEvent.getAction();
            ohos.data.distributed.device.DeviceInfo localDeviceInfo = KvManagerFactory.getInstance()
                    .createKvManager(new KvManagerConfig((this))).getLocalDeviceInfo();
            int localDeviceType = Integer.parseInt(localDeviceInfo.getType());
            ohos.global.resource.ResourceManager resManager = this.getResourceManager();
            try {
                text = resManager.getElement(ResourceTable.String_titles).getString();
                text1 = resManager.getElement(ResourceTable.String_titlex).getString();
            } catch (Exception e) {
                XLog.error(label, e.getMessage());
            }
            if (action == TouchEvent.PRIMARY_POINT_DOWN) {
                MmiPoint position = touchEvent.getPointerPosition(0);
                this.starx = position.getX();
                this.stary = position.getY();
            } else if (action == TouchEvent.PRIMARY_POINT_UP) {
                MmiPoint position = touchEvent.getPointerPosition(0);
                this.endx = position.getX();
                this.endy = position.getY();
                if (this.starx > this.endx && Math.abs(this.stary - this.endy) < 43 && Math.abs(this.starx - this.endx) > 163) {
                    final String text2 = "到头了...";
                    if (localDeviceType == DeviceInfo.DeviceType.PHONE.value()) {
                        new MyToastDialog(this.getContext(), text2, ResourceTable.Graphic_xtoast_framem, 40, 25)
                                .setDuration(120)
                                .setAlignment(LayoutAlignment.BOTTOM)
                                .setOffset(0, 100)
                                .show();
                        XLog.info(label, "当前设备类型为手机");
                    } else if (localDeviceType == DeviceInfo.DeviceType.TABLET.value()) {
                        new MyToastDialog(this.getContext(), text2, ResourceTable.Graphic_xtoast_framet, 48, 37)
                                .setDuration(120)
                                .setAlignment(LayoutAlignment.BOTTOM)
                                .setOffset(0, 100)
                                .show();
                        XLog.info(label, "当前设备类型为平板");
                    } else {
                        XLog.warn(label, "暂不支持您的设备:(" + localDeviceInfo.getType() + ")");
                        this.terminateAbility();
                    }
                    XLog.info(label, "左滑了");
                } else if (this.starx < this.endx && Math.abs(this.stary - this.endy) < 43 && Math.abs(this.starx - this.endx) > 163) {
                    this.ShowDialog("程序退出成功，感谢您的使用!");
                    this.terminateAbility();
                    XLog.info(label, "右滑了");
                } else if (this.stary > this.endy && Math.abs(this.starx - this.endx) < 123 && Math.abs(this.stary - this.endy) > 156)
                    XLog.info(label, "上滑了");
                else if (this.stary < this.endy && Math.abs(this.starx - this.endx) < 123 && Math.abs(this.stary - this.endy) > 156)
                    XLog.info(label, "下滑了");
                else XLog.info(label, "无效滑动（请直一点！）");
            } else XLog.info(label, "滑动中");
        } catch (Exception e) {
            AGConnectCrash.getInstance().recordException(e);
            XLog.error(label, e.getMessage());
        }
        return true;
    }


    /**
     * 展示数据
     *
     * @param text1 the text 1
     */
    private void ShowDialog(String text1) {
        try {
            ohos.data.distributed.device.DeviceInfo localDeviceInfo = KvManagerFactory.getInstance()
                    .createKvManager(new KvManagerConfig((this))).getLocalDeviceInfo();
            int localDeviceType = Integer.parseInt(localDeviceInfo.getType());
            if (localDeviceType == DeviceInfo.DeviceType.PHONE.value()) {
                new MyToastDialog(this.getContext(), text1, ResourceTable.Graphic_xtoast_framem, 36, 25)
                        .setDuration(120)
                        .setAlignment(LayoutAlignment.BOTTOM)
                        .setOffset(0, 100)
                        .show();
                XLog.info(label, "当前设备类型为手机");
            } else if (localDeviceType == DeviceInfo.DeviceType.TABLET.value()) {
                new MyToastDialog(this.getContext(), text1, ResourceTable.Graphic_xtoast_framet, 43, 37)
                        .setDuration(120)
                        .setAlignment(LayoutAlignment.BOTTOM)
                        .setOffset(0, 100)
                        .show();
                XLog.info(label, "当前设备类型为平板");
            } else {
                XLog.warn(label, "暂不支持您的设备:(" + localDeviceInfo.getType() + ")");
                this.terminateAbility();
            }
        } catch (Exception e) {
            AGConnectCrash.getInstance().recordException(e);
            XLog.error(label, e.getMessage());
        }
    }

    /**
     * 退出
     *
     * @param keyCode  the key code
     * @param keyEvent the key event
     * @return boolean boolean
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent keyEvent) {
        if (keyCode == KeyEvent.KEY_BACK) {
            this.ShowDialog("程序退出成功，感谢您的使用!");
            this.terminateAbility();
            return true;
        }
        return super.onKeyDown(keyCode, keyEvent);
    }
}